<?php

namespace app\common\model;

use think\Db;
use think\Model;

class ShippingTemplate extends Model
{
    // 表名
    protected $name = 'shipping_template';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'type_text',
        'is_free_text',
        'condition_free_text',
        'is_area_text'
    ];
    

    const TYPE_NUMBER = 1;
    const TYPE_WEIGHT = 2;
   //计算方式
    public function getTypeList()
    {
        return [self::TYPE_NUMBER => '按数量', self::TYPE_WEIGHT=>'按重量'];
    }     

    const FREE_N = 0;
    const FREE_Y = 1;
   //包含该商品时全订单包邮
    public function getIsFreeList()
    {
    	return [self::FREE_N => '否', self::FREE_Y => '是'];
    }

    const CONDETION_N = 0;
	const CONDETION_Y = 1;
    public function getConditionFreeList()
    {
    	return [self::CONDETION_N => '否', self::CONDETION_Y => '是'];
    }

    public function getIsAreaList()
    {
        return ['1' => __('Is_area 1')];
    }     


    public function getTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsFreeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_free'];
        $list = $this->getIsFreeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getConditionFreeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['condition_free'];
        $list = $this->getConditionFreeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsAreaTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['is_area'];
        $list = $this->getIsAreaList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	
	
    public function bus(){
    	return $this->belongsTo('business', 'business_id', 'id', '', 'left')->setEagerlyType(0);
    }
	/**
	 * 添加运费计算方式
	 * @param $tempId 模板ID
	 * @param $items 计算数组
	 * @param int $type 类型1添加2编辑
	 * @return bool
	 */
	public function addItems($tempId, $items, $type =1){
    	$model = Db::name('shippingTemplateItem');
    	if($type == 1){
		    $itemData = [];
		    foreach($items as $item){
			    unset($item['id']);
			    $item['template_id'] = $tempId;
			    $itemData[] = $item;
		    }
		    if($itemData){
			    $itemRes = $model->insertAll($itemData);
			    if(!$itemRes){
				    $this->error = '添加运费计算方式出错';
				    return false;
			    }
		    }
	    } else{
		    $rows = $model->where(['template_id' => $tempId])->select();
		    
    		$ids = [];
    		$itemData = [];
    	    foreach($items as $item){
		        if($item['id']){
		        	$ids[] = $item['id'];
		        	$res = $model->where(['id' => $item['id']])->update($item);
		        	if($res === false){
		        		$this->error = '更改运费计算方式出错';
		        		return false;
			        }
		        } else {
			        unset($item['id']);
			        $item['template_id'] = $tempId;
			        $itemData[] = $item;
		        }
	        }
	        if($itemData){
		        $itemRes = $model->insertAll($itemData);
		        if(!$itemRes){
			        $this->error = '添加运费计算方式出错';
			        return false;
		        }
	        }
    		
	        if($rows){
		        $delIds = [];
		        foreach($rows as $row){
			        if(!in_array($row['id'], $ids)){
				        $delIds[] = $row['id'];
			        }
		        }
		        if($delIds){
		        	$delRes = $model->where(['id'=>['in',$delIds]])->delete();
		        	if($delRes === false){
		        		$this->error = '删除运费计算方式出错';
		        		return false;
			        }
		        }
	        }
	    }
	    
	    return true;
	}
	
	
	/**
	 * 添加包邮条件
	 * @param $tempId 模板ID
	 * @param $items 条件数组
	 * @param int $type 类型1添加2编辑
	 * @return bool
	 */
	public function addConditions($tempId, $items, $type =1){
		$model = Db::name('shippingCondition');
		if($type == 1){
			$itemData = [];
			foreach($items as $item){
				unset($item['id']);
				$item['template_id'] = $tempId;
				$itemData[] = $item;
			}
			if($itemData){
				$itemRes = $model->insertAll($itemData);
				if(!$itemRes){
					$this->error = '添加免邮费条件出错';
					return false;
				}
			}
		} else{
			$rows = $model->where(['template_id' => $tempId])->select();
			$ids = [];
			$itemData = [];
			foreach($items as $item){
				if($item['id']){
					$ids[] = $item['id'];
					$res = $model->where(['id' => $item['id']])->update($item);
					if($res === false){
						$this->error = '更改免邮费条件出错';
						return false;
					}
				} else {
					unset($item['id']);
					$item['template_id'] = $tempId;
					$itemData[] = $item;
				}
			}
			if($itemData){
				$itemRes = $model->insertAll($itemData);
				if(!$itemRes){
					$this->error = '添加免邮费条件出错';
					return false;
				}
			}
			
			if($rows){
				$delIds = [];
				foreach($rows as $row){
					if(!in_array($row['id'], $ids)){
						$delIds[] = $row['id'];
					}
				}
				if($delIds){
					$delRes = $model->where(['id'=>['in',$delIds]])->delete();
					if($delRes === false){
						$this->error = '删除免邮费条件出错';
						return false;
					}
				}
			}
		}
		
		return true;
	}
	
	
	/**
	 *
	 * @param $goods
	 */
	public function shippingFree($goods, $provinceId){
		//不包邮数量
		$freeNumber = 0;
		//整个订单免费
		$orderFree = false;
		
		
		$freights = [];
		foreach($goods as $value){
			$freights[$value['goods_id']] = 0;
			
			//如果不包邮，不包邮数量加1
			if(!$value['is_free_shipping']){
//				echo $value['goods_id'].'不包邮<br>';
				$freeNumber ++;
			}
			$tempId = $value['shipping_template_id'];
			
			//没有模板直接跳过
			if(!$tempId){
//				echo $value['goods_id'].'运费模板不存在<br>';
				continue;
			}
			
			//查找运费模板
			$template = Db::name('shippingTemplate')->find($tempId);
//			dump($template);
			//如果设置了模板设置了包含此订单包邮，则这个订单的运费为0
			if($value['is_free_shipping'] && $template['is_free']){
//				echo '整个订单包邮<br>';
				$orderFree = true;
				break;
			}
			
			//商品重量
			$weight = $value['weight'] * $value['number'];
			
			//如果设置了满足条件包邮，查找包邮条件
			if($template['condition_free']){
//				echo '设置了满足条件包邮<br>';
				$condition = Db::name('shippingCondition')
					->where("template_id = ".$tempId." and ((area_ids is null) OR (area_ids = '') OR find_in_set('".$provinceId."', area_ids))")
					->order('area_ids DESC')
					->find();
				if($condition){
					//商品金额
					$conAmount = $value['price'] * $value['number'];
					
					if($condition['logic'] == 1 && $conAmount >= $condition['amount'] && $weight <= $condition['weight']){
//						echo '金额大于条件金额且重量小于条件重量<br>';
						$freights[$value['goods_id']] = 0;
					} elseif($condition['logic'] == 2 && $conAmount>= $condition['amount'] || $weight <= $condition['weight']){
//						echo '商品金额:'.$conAmount.'大于条件金额:'.$condition['amount'].'或重量:'.$weight.'小于条件重量:'.$condition['weight'].'<br>';
						$freights[$value['goods_id']] = 0;
					} else {
//						echo '不满足包邮条件<br>';
					}
				} else {
//					echo '找不到满足条件<br>'.Db::name('shippingCondition')->getLastSql();
				}
			}
			
			//查找计算方式
			$items = Db::name('shippingTemplateItem')
				->where("template_id = ".$tempId." and ((area_ids is null) OR (area_ids = '') OR find_in_set('".$provinceId."', area_ids))")
				->order('area_ids DESC')
				->find();
			if($items){
//				dump($items);
				//按件方式
				if($template['type'] == 1){
//					echo '按数量计算,商品数量'.$value['number'].'<br>';
//					echo $items['first'].'件内'.$items['amount'].'元，每多'.$items['add'].'件，增加'.$items['add_amount'].'元<br>';
					if($value['number'] <= $items['first']){
//						echo '小于首数量<br>';
						$amount = $items['amount'];
					} else {
//						echo '首件费用：'.$items['amount'].';续费：'.$items['add_amount'].'续件：'.$step.';<br>';
						$step = ceil(($value['number'] - $items['first'])/$items['add']);
						$amount = $items['amount']+$step*$items['add_amount'];
					}
				} else {
//					echo '按重量计算,商品重量：'.$weight.'<br>';
					//按重量
					if($weight <= $items['first']){
//						echo '小于等于首重<br>';
						$amount = $items['amount'];
					} else {
//						echo $items['first'].'g内'.$items['amount'].'元，每多'.$items['add'].'g，增加'.$items['add_amount'].'元<br>';
//						echo '重量：'.$weight.'<br>';
						$step = ceil(($weight - $items['first'])/$items['add']);
//						echo '续重：'.$step.'<br>';
						$amount = $items['amount']+$step*$items['add_amount'];
					}
				}
				$freights[$value['goods_id']] = $amount;
			} else {
//				echo '找不到计算运费方式<br>';
			}
		}
		
		//如果都是包邮的或整个订单包邮，所有商品邮费为0
//		echo '不包邮数量:'.$freeNumber.'<br>';
		if($freeNumber == 0 || $orderFree == true){
//			echo '订单包邮';
			foreach($goods as $good){
				$freights[$good['goods_id']] = 0;
			}
		}
		
		return $freights;
	}
}
